<template>
  <div>
    <el-dialog
      v-model="isShow"
      :title="$demoi18n('panel.thresholdSetting.dialogTitle')"
      width="630px"
      top="8.4vh"
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :class="`${customClass} ${visualThemeClassName} threshold-setting-table-dialog ${xvueNameSpace}`"
    >
      <div class="threshold-setting-main threshold-setting-grouping-uniuqe">
        <el-form
          ref="form"
          class="form"
          label-position="right"
          :model="thresholdForm"
          :rules="rules"
          label-width="85px"
        >
          <VsFormItem :label="$demoi18n('word.threshold')" class="el-form-grouping-switch">
            <el-switch v-model="thresholdForm.isThreshold"></el-switch>
          </VsFormItem>

          <div
            v-if="thresholdForm.isThreshold"
            class="config-table"
          >
            <!-- threshold-setting-grouping-uniuqe新增阈值 -->
            <el-button
              class="btn-sure button-sure"
              size="small"
              icon="CirclePlus"
              @click.stop="addNewRow(thresholdTemp, thresholdItem)"
            >{{ showGroup ? $demoi18n('panel.button.addGroup') : $demoi18n('btn.add') }}</el-button>
            <el-table
              ref="table"
              class="config-panel-table mapping-table"
              :data="thresholdForm.thresholdData"
              :row-style="{ height: '25px' }"
              :header-row-style="{ height: '25px' }"
              max-height="500"
              :header-cell-style="{ lineHeight: '15px' }"
            >
              <!-- 分组 -->
              <el-table-column
                v-if="showGroup"
                :label="$demoi18n('panel.label.grouping')"
                :min-width="170"
              >
                <template #header="{column}">
                  <ThCellTips :label="column.label" :tips="$demoi18n('panel.tip.thresholdGroupTip')" />
                </template>
                <template #default="scope">
                  <VsFormItem>
                    <ValueInputer
                      v-model:value="scope.row.name"
                      :enum-values="groupList"
                    />
                  </VsFormItem>
                </template>
              </el-table-column>
              <!-- 阈值区间 -->
              <el-table-column
                :label="$demoi18n('panel.label.thresholdRange')"
                :min-width="170"
              >
                <!-- threshold-setting-grouping header -->
                <template #header="{column}">
                  <el-tooltip
                    placement="top"
                    :content="`${column.label} eg: a <= x < b`"
                    :effect="xvueTheme"
                  >
                    <!-- threshold-setting-grouping表头 -->
                    <div style="display: inline-block; width: 100%; overflow:hidden; text-overflow: ellipsis;">
                      <span>{{ column.label }}</span>
                      <span
                        :style="{
                          fontSize: '12px',
                          marginLeft: '5px',
                          color: xvueTheme === 'dark'? '#fff': '#999',
                        }"
                      >eg: a &lt;= x &lt; b</span>
                      <!-- threshold-setting-grouping阈值描述 -->
                    </div>
                  </el-tooltip>
                </template>

                <template #default="scope">
                  <div class="threshold-column">
                    <VsFormItem
                      :prop="`thresholdData[${scope.$index}].min`"
                      :rules="genRulesByKey('threshold.min')"
                    >
                      <!-- threshold-setting-grouping num最小值 -->
                      <el-input-number
                        v-model="scope.row.min"
                        :placeholder="$demoi18n('panel.thresholdSetting.leftVal')"
                        size="small"
                        :style="{ width: '100%' }"
                        :controls="false"
                        @blur="checkThreshold"
                      ></el-input-number>
                    </VsFormItem>
                    <!-- threshold-setting-grouping num最大值 -->
                    <span :style="{ margin: '0 3px' }">-</span>
                    <VsFormItem
                      :prop="`thresholdData[${scope.$index}].max`"
                      :rules="genRulesByKey('threshold.max')"
                    >
                      <el-input-number
                        v-model="scope.row.max"
                        :placeholder="$demoi18n('panel.thresholdSetting.rightVal')"
                        size="small"
                        :controls="false"
                        :style="{ width: '100%' }"
                        @blur="checkThreshold"
                      ></el-input-number>
                    </VsFormItem>
                  </div>
                </template>
              </el-table-column>
              <!-- 进度条颜色 -->
              <el-table-column
                prop="color"
                :label="$demoi18n('panel.fieldSetting.progressColor')"
                :align="'center'"
                :min-width="55"
              >
                <template #header="{column}">
                  <ThCell :label="column.label" />
                </template>
                <template #default="scope">
                  <el-color-picker
                    v-model="scope.row.color"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    color-format="hex"
                    :style="{ 'vertical-align': 'bottom' }"
                    :predefine="predefineColors"
                    size="small"
                    append-to=".threshold-setting-table-dialog"
                  ></el-color-picker>
                </template>
              </el-table-column>
              <!-- 操作 -->
              <el-table-column :label="$demoi18n('word.operation')" :min-width="30">
                <template #header="{column}">
                  <ThCell :label="column.label" />
                </template>
                <template #default="scope">
                  <el-button
                    icon="Delete"
                    :link="true"
                    type="primary"
                    @click.stop="deleteCurRow(scope.$index)"
                  ></el-button>
                  <!-- threshold-setting-grouping删除 -->
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
        <div class="action-button-group threshold-setting-grouping-unique">
          <el-button
            class="button-sure"
            size="small"
            type="primary"
            @click="handleSave()"
          >{{
            $demoi18n('btn.confirm')
          }}</el-button>
          <el-button
            class="button-cancel threshold-setting-grouping-unique"
            size="small"
            @click="cancel()"
          >{{ $demoi18n('btn.close') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ThCell from '@/components/common/th-cell/th-cell.vue';
import ThCellTips from '@/components/common/th-cell/th-cell-tips.vue';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import { fieldTypeOptions } from '@/components/panel-data/components/table-column-default-config';
import { genRulesByKey } from '@/utils/rules';
import { mapState } from 'vuex';

export default {
  name: 'ThresholdSetting',
  components: { ValueInputer, ThCell, ThCellTips },
  props: ['form', 'config', 'activeColorRadio', 'activeColorSwitch', 'nameList', 'fieldList', 'tableData', 'useFor', 'showGroup'],
  emits: ['save'],
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      xvueTheme: window._adoPremise.uc.theme,
      customClass: `threshold-setting-dialog threshold-setting-dialog-${window._adoPremise.uc.theme || 'light'}`,
      isShow: false,
      thresholdForm: {},
      thresholdItem: {
        name: '',
        min: 0,
        max: 0,
        color: '',
      },
      thresholdTemp: {},
      dataTypeOptions: fieldTypeOptions,
      predefineColors: ['#ff5071'],
      rules: {},
      groupList: [],
    };
  },
  computed: {
    ...mapState({
      componentsData: state => state.VisualComponentsModule.componentsData,
    }),
  },
  methods: {
    genRulesByKey,
    openDialog() {
      this.groupList = [];
      const { data, isThreshold, threshold } = this.form;
      const thresholdData = JSON.parse(JSON.stringify(threshold));
      if (data && data.length > 0) {
        data.forEach(item => {
          this.groupList.push(item.name);
        });
      }
      this.thresholdForm = {
        isThreshold,
        thresholdData,
      };
      this.isShow = true;
    },

    addNewRow(temp, item) {
      const threTemp = JSON.parse(JSON.stringify(item));
      this.thresholdForm.thresholdData.push(threTemp);
    },
    cancel() {
      this.isShow = false;
    },
    deleteCurRow(index) {
      this.thresholdForm.thresholdData.splice(index, 1);
      this.checkThreshold();
    },
    checkThreshold() {
      const { thresholdData } = this.thresholdForm;
      let errorText = '';

      // 遍历各数据类型各自校验
      const groupNameSet = new Set(thresholdData.map(num => num.name));
      const groupNameArr = Array.from(groupNameSet);

      // 遍历各字段各自校验
      for (let i = 0; i < groupNameArr.length; i++) {
        const curFieldArr = thresholdData.filter(num => num.name === groupNameArr[i]);
        const rangeArray = [];
        curFieldArr.forEach((item, index) => {
          rangeArray[index] = [item.min, item.max];
        });

        // 校验错误区间
        for (let j = 0; j < rangeArray.length; j++) {
          if (rangeArray[j][0] >= rangeArray[j][1]) {
            errorText = this.$demoi18n('message.wrongThresholdRange');
            this.emitToPanel(errorText);
            return false;
          }
        }

        // 校验重复区间
        if (!this.checkNumThresholdRepetition(rangeArray)) {
          return false;
        }
      }
      return true;
    },
    checkNumThresholdRepetition(rangeArray) {
      let errorMes = '';
      for (let i = 0; i < rangeArray.length; i++) {
        for (let j = 0; j < i; j++) {
          if (
            (rangeArray[i][0] >= rangeArray[j][0] && rangeArray[i][0] < rangeArray[j][1]) ||
                (rangeArray[i][1] > rangeArray[j][0] && rangeArray[i][1] < rangeArray[j][1])
          ) {
            errorMes = this.$demoi18n('message.thresholdRepetition');
            this.emitToPanel(errorMes);
            return false;
          }
        }
      }
      return true;
    },
    emitToPanel(error) {
      this.$message.error(error);
    },

    handleSave() {
      if (!this.thresholdForm.isThreshold || this.thresholdForm.thresholdData.length === 0) {
        this.$emit('save', this.thresholdForm);
        this.cancel();
        return;
      }
      this.$refs.form.validate(valid => {
        if (!valid || !this.checkThreshold()) {
          return;
        }
        this.$emit('save', this.thresholdForm);
        this.cancel();
      });
    },
  },
};
</script>

<style lang="less">
@import '../../../common/color-picker-panel.less';
</style>
<style lang="less" scoped>
// .threshold-setting-dialog {
  .threshold-setting-main {
    .form {
      width: 100%;
      :deep(.el-form-item) {
        margin-bottom: 0;

        .el-form-item__label {
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }

      .el-form-grouping-switch {
        align-items: center;
      }

      .config-table {
        :deep(.el-table) {
          .el-form-item__error {
            top: 100%;
            padding-top: 0;
            white-space: normal;
            word-break: break-word;
          }
          .is-error {
            margin-bottom: 15px;
          }
          .cell {
            padding: 0 3px !important;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            .threshold-column {
              display: flex;
              align-items: center;
              .threshold-column-select {
                display: contents;
              }
            }
            .el-input__inner {
              padding: 0 5px !important;
            }
          }
          td,
          th {
            padding: 5px 0 !important;
          }
          th div {
            line-height: 15px;
          }
          .el-table__row > td {
            border: none;
          }
        }
        :deep(.el-form-item__content) {
          margin-left: 0 !important;
        }
      }
    }
  }

  .action-button-group {
    text-align: right;
    padding-top: 20px;
    .button-sure {
      padding: 9px 35px;
      border-radius: 0;
    }
    .button-cancel {
      padding: 9px 35px;
      border-radius: 0;
    }
  }
// }
.icon-library-dialog-dark {
  .icon-library-main {
    background-color: #071f30;
  }
  .action-button-group {
    .button-sure {
      background-color: #0eb4c2;
      color: #fff;
    }
    .button-cancel {
      background-color: #064559;
      border-color: #064559;

      color: #fff;
    }
  }
}
</style>
